package com.talent.jiwen_teacher.my;

import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.abc.live.ABCLiveUIHelp;
import com.abc.live.widget.common.ABCLiveControllerView;
import com.abcpen.core.define.ABCConstants;
import com.abcpen.open.api.model.RoomMo;
import com.talent.jiwen_teacher.ActivityManager;
import com.talent.jiwen_teacher.ChangePasswordActivity;
import com.talent.jiwen_teacher.LoginActivity;
import com.talent.jiwen_teacher.R;
import com.talent.jiwen_teacher.base.BaseActivity;
import com.talent.jiwen_teacher.chatlive.TestInteractiveActivity;
import com.talent.jiwen_teacher.http.common.UpdateAppHttpUtil;
import com.talent.jiwen_teacher.util.CommonUtils;
import com.talent.jiwen_teacher.util.SPConstant;
import com.talent.jiwen_teacher.util.SPUtil;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.listener.IUpdateDialogFragmentListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.talent.jiwen_teacher.my.WebShowActivity.WEB_BOOK_INTRODUCE;
import static com.talent.jiwen_teacher.my.WebShowActivity.WEB_SHOW_TYPE;

/**
 * Created by qyqx on 2018/8/10.
 * 设置界面
 */

public class SetActivity extends BaseActivity {

    @BindView(R.id.rl_changePhone)
    RelativeLayout rl_changePhone;
    @BindView(R.id.txt_phone)
    TextView txt_phone;
    @BindView(R.id.rl_changePwd)
    RelativeLayout rl_changePwd;
    @BindView(R.id.txt_version)
    TextView txt_version;
    @BindView(R.id.bt_quit)
    Button bt_quit;


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_set;
    }

    @Override
    public String titleName() {
        return "设置";
    }

    @Override
    protected void initData() {

        txt_phone.setText(SPUtil.getUserPhone());
        txt_version.setText("v"+CommonUtils.getLocalVersionName(mContext));

    }

    @OnClick({R.id.rl_changePhone, R.id.rl_changePwd, R.id.bt_quit,R.id.rl_about,R.id.rl_nowVersion,R.id.rl_adr,R.id.rl_feedback,R.id.rl_test,R.id.rl_introduce})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_changePhone:
//                intentActivity(EvaluateActivity.class);
//                showSharePop();
                break;
            case R.id.rl_changePwd:
                intentActivity(ChangePasswordActivity.class);
                break;
            case R.id.bt_quit:
//                JPushInterface.setAlias(mContext , (int)Math.random(), "");
//                JPushInterface.deleteAlias(mContext , (int)Math.random());
                SPUtil.clearAll();
                ActivityManager.getAppManager().finishAllActivity();
                intentActivity(LoginActivity.class);
                finish();
                break;

            case R.id.rl_about://关于我们
                intentActivity(AboutUsActivity.class);
                break;
            case R.id.rl_nowVersion://当前版本
                showUpdate();
                break;
            case R.id.rl_adr:
                intentActivity(PenAdrActivity.class);
                break;
            case R.id.rl_feedback:
                intentActivity(FeedbackActivity.class);
                break;
            case R.id.rl_test:
                ABCLiveControllerView.isHiddenController=true;
                goLive();
                break;
            case R.id.rl_introduce:
                WEB_SHOW_TYPE=WEB_BOOK_INTRODUCE;
               intentActivity(WebShowActivity.class);
                break;
        }
    }




    public void goLive() {
        String rid = SPUtil.getBSUId();
        int liveType = 2;
        ABCLiveUIHelp uiHelp = ABCLiveUIHelp.init()
                .setUserID(SPUtil.getBSUId())
                .setUserName(SPUtil.getUserName())
                .setIsManager(false)
                .setDefaultOpenCamera(true)
                .setDefaultOpenMic(true);

        RoomMo roomMo = new RoomMo();
        roomMo.room_id = rid;
        roomMo.name = "测试房间";
        roomMo.live_type = liveType;
        ABCLiveUIHelp abcLiveUIHelp = null;
        if(!SPUtil.booleanDataOut(SPConstant.IS_FIRST_GUIDE)){
            abcLiveUIHelp= uiHelp.setIsShowGuide(true);
            SPUtil.booleanDataIn(SPConstant.IS_FIRST_GUIDE,true);
        }else{
            abcLiveUIHelp= uiHelp.setIsShowGuide(false);
        }
        abcLiveUIHelp.setIsManager(false);
        roomMo.isRecord =2 ;//isRecording ? 1 : 2
        abcLiveUIHelp.setUserIconDefault(R.drawable.abc_default_icon);
        abcLiveUIHelp.setUserAvatarUrl(SPUtil.getUserHeadImg());
//        abcLiveUIHelp.setEndTime(System.currentTimeMillis() + 45 * 1000);
        abcLiveUIHelp.setStartTime(System.currentTimeMillis() + 10 * 1000);
        abcLiveUIHelp.setRoleType(ABCConstants.HOST_TYPE);
        abcLiveUIHelp.startInteractiveLiveActivity(SetActivity.this, roomMo, TestInteractiveActivity.class);
    }




    /**版本更新
     *
     */
    private void showUpdate(){

        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        Map<String, String> params = new HashMap<String, String>();
        params.put("application_type", "4");

        new UpdateAppManager
                .Builder()
                //必须设置，当前Activity
                .setActivity(this)
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl("abcd")
                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(true)
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //设置点击升级后，消失对话框，默认点击升级后，对话框显示下载进度
//                .hideDialogOnDownloading()
                //设置头部，不设置显示默认的图片，设置图片后自动识别主色调，然后为按钮，进度条设置颜色
                .setTopPic(R.mipmap.top_5)
                //为按钮，进度条设置颜色，默认从顶部图片自动识别。
                //.setThemeColor(ColorUtil.getRandomColor())
                //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
                .setTargetPath(path)
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
                //.setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")
                //不显示通知栏进度条
                .dismissNotificationProgress()
                //是否忽略版本
                //.showIgnoreVersion()
                .setUpdateDialogFragmentListener(new IUpdateDialogFragmentListener() {
                    @Override
                    public void onUpdateNotifyDialogCancel(UpdateAppBean updateApp) {
                        //用户点击关闭按钮，取消了更新，如果是下载完，用户取消了安装，则可以在 onActivityResult 监听到。

                    }
                })
                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 解析json,自定义协议
                     *
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            updateAppBean
                                    //（必须）是否更新Yes,No
                                    .setUpdate(jsonObject.optString("update"))
                                    //（必须）新版本号，
                                    .setNewVersion(jsonObject.optString("new_version"))
                                    //（必须）下载地址
                                    .setApkFileUrl(jsonObject.optString("apk_file_url"))
                                    //（必须）更新内容
                                    .setUpdateLog(jsonObject.optString("update_log"))
                                    //大小，不设置不显示大小，可以不设置
                                    .setTargetSize(jsonObject.optString("target_size"))
                                    //是否强制更新，可以不设置
                                    .setConstraint(false)
                                    //设置md5，可以不设置
                                    .setNewMd5(jsonObject.optString("new_md51"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        return updateAppBean;
                    }

                    @Override
                    protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        updateAppManager.showDialogFragment();
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
//                        CProgressDialogUtils.showProgressDialog(LoginActivity.this);
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
//                        CProgressDialogUtils.cancelProgressDialog(LoginActivity.this);
                    }
//
                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp(String error) {
                        Toast.makeText(SetActivity.this, error, Toast.LENGTH_SHORT).show();
                    }
                });

    }


}
